<template>
  <section>
    <a-modal
      :maskClosable="false"
      :width="1000"
      :title="isEdit ? '编辑会员信息' : '新建会员信息'"
      :confirm-loading="confirmLoading"
      okType="primary"
      v-model="showModal"
      @ok="confirmOk"
      @cancel="cancel"
    >
      <a-form :form="form">
        <a-divider class="divider" style="margin-top: 0;">必填信息</a-divider>
        <a-row :gutter="[16,0]">
          <a-col :span="8">
            <a-form-item class="mb-15" label="会员姓名" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input
                placeholder="请输入会员姓名"
                v-decorator="[
							'name',
							{rules: [{required: true, message: '请输入会员姓名', whitespace: true}]}
						]"
                maxLength="20"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item class="mb-15" label="联系电话" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input
                placeholder="请输入联系电话"
                v-decorator="[
                  'phone',
                  {rules: [{required: true, message: '请输入联系电话', whitespace: true,validator: $utils.phoneValidator}]}
                ]"
                maxLength="20"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item class="mb-15" label="会员渠道" :label-col="labelCol" :wrapper-col="wrapperCol">
              <!-- <a-select
                placeholder="请选择会员渠道"
                v-decorator="[
                  'channelId',
                  {rules: [{required: true, message: '请选择会员渠道'}]}
                ]">
                <a-select-option :value="0">平台下单</a-select-option>
                <a-select-option v-for="item in allChannel" :value="item.id" :key="item.name">
                  {{ item.name }}
                </a-select-option>
              </a-select> -->
			  <sourceChannel ref="channes" placeholder="请选择会员渠道"
			          v-model="channelId" isShow="true"
			          :options="{ allowClear: true }"
			          @change="search" class="flex-1 overflow-hidden" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider class="divider">基本信息</a-divider>
        <a-row :gutter="[16,0]">
          <a-col :span="8">
            <a-form-item class="mb-15" label="会员邮箱" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input
                placeholder="请输入会员邮箱"
                v-decorator="[
							'email',
							{rules: [{message: '请输入会员邮箱',type: 'email',}]}
						]"
                maxLength="100"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item class="mb-15" label="紧急联系人" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input
                placeholder="请输入紧急联系人"
                v-decorator="[
							'emergencyContactsName',
							{rules: [{message: '请输入紧急联系人'}]}
						]"
                maxLength="20"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item class="mb-15" label="联系人电话" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input
                placeholder="请输入联系人电话"
                v-decorator="[
							'emergencyContactsPhone',
							{rules: [{message: '请输入联系人电话',validator: phoneValidator}]}
						]"
                maxLength="20"
              ></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="[16,0]">
          <a-col :span="8">
            <a-form-item class="mb-15" label="证件类型" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-select
                placeholder="请选择证件类型"
                v-decorator="[
							'credentialType'
						]"
              >
                <a-select-option v-for="item in credentialsList" :key="item.value" :value="item.value">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item class="mb-15" label="证件号码" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input
                placeholder="请输入证件号码"
                v-decorator="[
							'credentialNo',
							{rules: [{message: '请输入证件号码'}]}
						]"
                maxLength="20"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item class="mb-15" label="证件有效期" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-date-picker
                class="w-full"
                placeholder="请选择证件有效期"
                v-decorator="[
							'credentialEffectiveTime'
						]"
              ></a-date-picker>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="[16,0]">
          <a-col :span="8">
            <a-form-item class="mb-15" label="驾照类型" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-select
                placeholder="请选择驾照类型"
                v-decorator="[
							'driverLicenseType'
						]"
              >
                <a-select-option v-for="item in drivingLicenseList" :key="item.value" :value="item.value">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item class="mb-15" label="领取日期" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-date-picker
                class="w-full"
                placeholder="请选择领取日期"
                @change="handleStartChange"
                v-decorator="[
							'driverLicenseGetTime'
						]"
              ></a-date-picker>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item class="mb-15" label="驾照有效期" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-date-picker
                class="w-full"
                :disabled-date="disabledEndDate"
                placeholder="请选择驾照有效期"
                @change="handleEndChange"
                v-decorator="[
							'driverLicenseEffectiveTime'
						]"
              ></a-date-picker>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="[24,0]">
          <a-col :span="12">
            <a-form-item class="mb-15 upload-list" :colon="false">
              <template #label>
                <p class="ml-20 mb-0">身份证件<span class="ml-5 num-color">{{ fileListA.length }}/2</span></p>
              </template>
              <section class="flex">
                <multipleShowList ref="fileListA" :scene="1" @uploadSuccess="uploadAvatarSuccessA"
                                  @removeFile="removeFileA"/>
                <div
                  class="ant-upload-list-picture-card-container ant-upload-select ant-upload-list ant-upload-list-picture-card examples-img">
                  <div class="ant-upload-list-item ant-upload-list-item-list-type-picture-card">
                    <div class="ant-upload-list-item-info">
                      <img style="width:70px;" src="~@/assets/examples.png" alt="示例图">
                      <span><i class="anticon anticon-picture ant-upload-list-item-thumbnail"></i><span title="示例图"
                                                                                                        class="ant-upload-list-item-name">示例图</span></span>
                    </div>
                    <span class="ant-upload-list-item-actions"><a title="预览文件" href="javascript:"
                                                                  @click="handlePreview('../../../assets/examples.png')"><i
                      class="anticon anticon-eye-o"><a-icon style="color: #fff;" type="eye"/></i></a></span></div>
                </div>
              </section>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item class="mb-15 upload-list" :colon="false">
              <template #label>
                <p class="ml-20 mb-0">驾驶证件<span class="ml-5 num-color">{{ fileListB.length }}/2</span></p>
              </template>
              <section class="flex">
                <multipleShowList ref="fileListB" :scene="3" @uploadSuccess="uploadAvatarSuccessB"
                                  @removeFile="removeFileB"/>
                <div
                  class="ant-upload-list-picture-card-container ant-upload-select ant-upload-list ant-upload-list-picture-card examples-img">
                  <div class="ant-upload-list-item ant-upload-list-item-list-type-picture-card">
                    <div class="ant-upload-list-item-info">
                      <img style="width:70px;" src="~@/assets/examples.png" alt="示例图">
                      <span><i class="anticon anticon-picture ant-upload-list-item-thumbnail"></i><span title="示例图"
                                                                                                        class="ant-upload-list-item-name">示例图</span></span>
                    </div>
                    <span class="ant-upload-list-item-actions"><a title="预览文件" href="javascript:"
                                                                  @click="handlePreview('@/assets/examples.png')"><i
                      class="anticon anticon-eye-o"><a-icon style="color: #fff;" type="eye"/></i></a></span></div>
                </div>
              </section>
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider class="divider">银行卡信息</a-divider>
        <section class="flex">
          <div class="ant-form-item-label ml-20"><label title="银行卡号" class="">银行卡号</label></div>
          <section>
            <template v-if="info.bankCards">
              <section class="cards-list" v-for="(item,index) in info.bankCards" :key="index">
                <a-form-item style="width:330px;" class="mb-10">
                  <a-input
                    v-model="item.cardNo"
                    maxLength="20"
                    placeholder="请输入银行卡号"
                  />
                </a-form-item>
                <span class="between-line">--</span>
                <a-form-item style="width:180px;" class="mb-10" :label-col="{ span:0 }">
                  <a-date-picker
                    class="w-full"
                    placeholder="请选择有效日期"
                    v-model="item.cardEffectiveTime"
                  ></a-date-picker>
                </a-form-item>
                <a-popconfirm title="确定要删除吗？" ok-text="是" cancel-text="否" @confirm="removeBankCards(index)">
        <span class="text-red-700 action">
          <a-icon type="minus-square"/>
        </span>
                </a-popconfirm>
              </section>
            </template>
            <a-button type="dashed" class="w564" @click="addbankCards">
              + 添加
            </a-button>
          </section>
        </section>
      </a-form>
    </a-modal>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage"/>
    </a-modal>
  </section>
</template>

<script>
import {createMemberInfo, editMemberInfo, getMemberInfo,getAllEnabledChannel} from '@/api/memberInfo'
import moment from 'moment'
import {omit, cloneDeep} from 'lodash'
import sourceChannel from '@/components/sourceChannel'
import Upload from '@/components/Upload'
import multipleShowList from '@/components/Upload/multipleShowList'

export default {
  name: 'MemberInfoCreateOrEdit',
  components: {Upload, multipleShowList,sourceChannel},
  props: {
    credentialsList: {
      type: Array,
      default: () => []
    },
    drivingLicenseList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      labelCol: {span: 7},
      wrapperCol: {span: 17},
      isEdit: false,
      showModal: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      fileListA: [],
      fileListB: [],
      previewVisible: false,
      isUp: false,
      info: {},
	   channelId: undefined,
      startValue: null,
      endValue: null,
      examples: require('@/assets/examples.png')
    }
  },
  created() {
    // getAllEnabledChannel().then(res => {
    //   this.allChannel = res
    // })
  },
  methods: {
    handleCancel() {
      this.previewVisible = false
    },
    handlePreview() {
      this.previewImage = this.examples
      this.previewVisible = true
    },
    removeFileB(data) {
      this.fileListB.splice(this.fileListB.findIndex(item => item.uid === data.uid), 1)
    },
    uploadAvatarSuccessB(data) {
      this.fileListB = data
    },
    removeFileA(data) {
      this.fileListA.splice(this.fileListA.findIndex(item => item.uid === data.uid), 1)
    },
    uploadAvatarSuccessA(data) {
      this.fileListA = data
    },
    handleEndChange(e) {
      this.endValue = e
    },
    handleStartChange(e) {
      this.startValue = e
    },
    disabledStartDate(startValue) {
      const endValue = this.endValue
      if (!startValue || !endValue) {
        return moment(new Date()).valueOf() > startValue.valueOf()
      }
      return startValue.valueOf() > endValue.valueOf() || moment(new Date()).valueOf() > startValue.valueOf()
    },
    disabledEndDate(endValue) {
      const startValue = this.startValue
      if (!endValue || !startValue) {
        return moment(new Date()).valueOf() > endValue.valueOf()
      }
      return startValue.valueOf() >= endValue.valueOf() || moment(new Date()).valueOf() > endValue.valueOf()
    },
    phoneValidator(rule, value, callback) {
      const phone = value && value.trim()
      const isMobile = /^1[3|5|8]\d{9}$/
      const isZuoji = /^0\d{2,3}-?\d{7,8}$/
      const isZuoji2 = /\d{6,8}/
      if (phone && !isMobile.test(phone) && !isZuoji.test(phone) && !isZuoji2.test(phone)) {
        callback(new Error('请输入正确的联系电话'))
      } else {
        callback()
      }
    },
    addbankCards() {
      if (!this.info.bankCards) this.info = {...this.info, bankCards: []}
      this.info.bankCards.push({
        customerId: '',
        cardNo: '',
        cardEffectiveTime: ''
      })
    },
    add() {
      this.isEdit = false
      this.showModal = true
	  this.$nextTick(() => {
	    this.$refs.channes.getId()
	      
	   })
    },
    edit(id) {
      this.isEdit = true
	 
      getMemberInfo({id}).then(res => {
        this.showModal = true
        const {
          driverLicenseType,
          credentialType,
          credentialPicFilePathA,
          credentialPicFilePathB,
          driverLicensePicFilePathA,
          driverLicensePicFilePathB
        } = res
        res.driverLicenseType = this.drivingLicenseList.findIndex(item => item.value === driverLicenseType) >= 0 ? driverLicenseType : undefined
        res.credentialType = this.credentialsList.findIndex(item => item.value === credentialType) >= 0 ? credentialType : undefined
        this.info = res
        this.$nextTick(() => {
          const fileListA = []
          if (credentialPicFilePathA) fileListA.push({
            url: credentialPicFilePathA,
            uid: this.$utils.uuid(),
            name: 'image.png',
            status: 'done',
          })
          if (credentialPicFilePathB) fileListA.push({
            url: credentialPicFilePathB,
            uid: this.$utils.uuid(),
            name: 'image.png',
            status: 'done',
          })
          const fileListB = []
          if (driverLicensePicFilePathA) fileListB.push({
            url: driverLicensePicFilePathA,
            uid: this.$utils.uuid(),
            name: 'image.png',
            status: 'done',
          })
          if (driverLicensePicFilePathB) fileListB.push({
            url: driverLicensePicFilePathB,
            uid: this.$utils.uuid(),
            name: 'image.png',
            status: 'done',
          })
          this.fileListA = fileListA
          this.fileListB = fileListB
          this.$refs.fileListA.setFileList(fileListA)
          this.$refs.fileListB.setFileList(fileListB)
          res.cardNo = []
          res.cardEffectiveTime = []
          res.customerId = []
          res.bankCards.forEach(item => {
            res.cardNo.push(item.cardNo)
            res.customerId.push(item.customerId)
            res.cardEffectiveTime.push(item.cardEffectiveTime ? moment(item.cardEffectiveTime) : '')
          })
		  this.channelId=res.channelId
          this.form.setFieldsValue({...this.$utils.valueToNull(cloneDeep(res))})
        })
      })
	  this.$nextTick(() => {
	    this.$refs.channes.getId()
	      
	   })
    },
    cancel() {
      this.showModal = false
      this.isEdit = false
      this.startValue = null
      this.endValue = null
      this.confirmLoading = false
      this.fileListA = []
      this.$refs.fileListA.setFileList([])
      this.fileListB = []
      this.$refs.fileListB.setFileList([])
      this.info.bankCards = []
      this.form.resetFields()
    },
    repetBankCards(data) {
      const dataIndex = []
      const datas = data.map((item, index) => ({...item, index: index + 1}))
      datas.forEach((item, key) => {
        dataIndex.push(datas.filter((l, index) => !(l.cardNo === item.cardNo && item.index === l.index)).some(l => l.cardNo === item.cardNo))
      })
      return dataIndex.some(item => item)
    },
    confirmOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          const {isEdit, fileListA, fileListB, info} = this
          const {driverLicenseGetTime, driverLicenseEffectiveTime} = values
          if (driverLicenseGetTime && driverLicenseEffectiveTime && driverLicenseGetTime.valueOf() > driverLicenseEffectiveTime.valueOf()) {
            this.$message.warning('驾照有效期不能小于领取日期之后！')
            return false
          }
          let bankCards = []
          if (info.bankCards && info.bankCards.length) {
            bankCards = info.bankCards.map(item => {
              return {
                cardNo: item.cardNo && item.cardNo.trim(),
                cardEffectiveTime: item.cardEffectiveTime ? moment(item.cardEffectiveTime).format('YYYY-MM-DD') : '',
                customerId: item.customerId ? item.customerId : 0
              }
            }).filter(item => item.cardNo)
            if (bankCards.length && this.repetBankCards(bankCards)) {
              this.$message.warning('银行卡号重复！')
              this.confirmLoading = false
              return false
            }
          }
          this.confirmLoading = true
          const fun = isEdit ? editMemberInfo : createMemberInfo
          fun(omit({
            ...this.$utils.trimValue(values, true),
            bankCards,
            id: isEdit ? this.info.id : undefined,
			channelId:this.channelId,
            credentialPicFilePathA: fileListA[0] ? fileListA[0].url : '',
            credentialPicFilePathB: fileListA[1] ? fileListA[1].url : '',
            driverLicensePicFilePathA: fileListB[0] ? fileListB[0].url : '',
            driverLicensePicFilePathB: fileListB[1] ? fileListB[1].url : ''
          }, ['cardEffectiveTime', 'cardNo', 'customerId'])).then((res) => {
            this.$message.success(isEdit ? '编辑成功！' : '新建成功！')
            this.$emit('search')
            this.cancel()
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    removeBankCards(index) {
      this.info.bankCards.splice(index, 1)
    }
  }
}
</script>

<style lang="less" scoped>
.flex {
  display: flex;
}

.divider::before, .divider::after {
  top: 9%;
}

.num-color {
  font-weight: 700;
  color: rgba(127, 127, 127, 0.8);
}

.upload-list {
  /deep/ .ant-form-item-label {
    line-height: normal;
  }
}


.avatar-uploader {
  width: auto;
}

.ant-upload-list-item-name {
  bottom: 0px !important;
}

.cards-list {
  display: flex;

  .action {
    padding-left: 10px;
    line-height: 38px;
    cursor: pointer;
  }

  .between-line {
    display: block;
    width: 30px;
    line-height: 35px;
    text-align: center;
  }
}

.w564 {
  margin-top: 5px;
  width: 564px;
}

.ant-upload-list-picture-card .ant-upload-list-item {
  width: 88px !important;
  height: 88px !important;
}

</style>
